package com.xhtranslate.common.util;

import com.xhtranslate.common.config.TranslateConfig;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author liuxuhuang
 * @version 1.0
 * @package com.xhtranslate.common.util
 * @date 2022/11/22 21:37:55
 * @description 减少redis免费额度多线程工具栏
 */
@Component
public class AddUseLimitThreadUtil {
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 增加使用额度
     *
     * @param redisName
     * @param length
     */
    @Async(value = "addCreditLimitExecutor")
    public void addCreditLimit(String redisName, int length) {
        if (!StringUtil.isNullOrEmpty(redisUtil.get(redisName).toString())) {
            int value = (int) redisUtil.get(redisName);
            value += length;
            if (value < getRedisLimitNumber(redisName)) {
                redisUtil.set(redisName, value);
            } else {
                redisUtil.set(redisName, 0);
            }
        } else {
            redisUtil.set(redisName, 0);
        }

    }

    public int getRedisLimitNumber(String name) {
        switch (name) {
            case TranslateConfig.BaiduOcrRedisName:
                return TranslateConfig.BaiduOcrRedisCreditLimit;
            case TranslateConfig.BaiduTextTranslateRedisName:
                return TranslateConfig.BaiduTextTranslateRedisCreditLimit;
            case TranslateConfig.AliOcrRedisName:
                return TranslateConfig.AliOcrRedisCreditLimit;
            case TranslateConfig.AliTextTranslateRedisName:
                return TranslateConfig.AliTextTranslateRedisCreditLimit;
            case TranslateConfig.YoudaoOcrRedisName:
                return TranslateConfig.YoudaoOcrRedisCreditLimit;
            case TranslateConfig.YoudaoTextTranslateRedisName:
                return TranslateConfig.YoudaoTextTranslateRedisCreditLimit;
            default:
                return 0;
        }
    }
}
